package com.zzxy.spring12.aspect;

import com.zzxy.spring12.service.ITeacherService;
import com.zzxy.spring12.service.impl.TeacherServiceImpl;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class MyBeanFactory {
    public static ITeacherService createTeacherService() {
        // 1.target class
        ITeacherService teacherService = new TeacherServiceImpl();
        //2. advice
        MyAspect aspect = new MyAspect();
        //3. weaving > teacherServiceProxy
        ITeacherService proxy = (ITeacherService) Proxy.newProxyInstance(MyBeanFactory.class.getClassLoader(), teacherService.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        aspect.before();
                        Object obj = method.invoke(teacherService, args);
                        aspect.after();
                        return obj;
                    }
                });

        return proxy;
    }
}
